package service

import (
	"errors"
	"github.com/tarm/serial"
	"iot-base/common/cache"
	"iot-base/common/logger"
	"iot-base/common/notify"
	"iot-base/common/serialdata"
	"strconv"
	"time"
)

var typeMap = map[string]string{
	"serial": "本机串口",
	"tcp":    "串口服务器",
}

func ReportDataFloat64(id string, data []string, mapField map[int]string) {
	now := time.Now().Unix()
	for k, v := range data {
		value, _ := strconv.ParseFloat(v, 64)
		if field, ok := mapField[k+1]; ok {
			notify.RawData(id, field, "", 0, value, now, now)
		}
	}
}

func ReportDataString(id string, data []string, mapField map[int]string) {
	now := time.Now().Unix()
	for k, v := range data {
		if field, ok := mapField[k+1]; ok {
			notify.RawData(id, field, "", 0, v, now, now)
		}
	}
}

func RequestData(thing *cache.ThingInfo, isService bool, msg []byte) ([]byte, error) {

	ip := thing.GetThingParam("ip", "")
	port := thing.GetThingParam("port", "")
	//波特率
	baudRate := thing.GetThingParam("BaudRate", "")
	baud, _ := strconv.Atoi(baudRate)
	//串口名
	name := thing.GetThingParam("Name", "")
	//数据位
	dataBits := thing.GetThingParam("DataBits", "")
	size, _ := strconv.Atoi(dataBits)
	//校验位
	parity := thing.GetThingParam("Parity", "")
	//停止位
	stopBits := thing.GetThingParam("StopBits", "")
	//类型
	tType := thing.GetThingParam("type", "")
	if tType == "" {
		return []byte{}, errors.New("type is empty")
	}
	conf := serial.Config{
		Name:        name,
		Baud:        baud,
		ReadTimeout: 0,
		Size:        byte(size),
		Parity:      serialdata.ParseParity(parity),
		StopBits:    serialdata.ParseStopBit(stopBits),
	}
	dataFrame := serialdata.DataFrame{
		Mod:    tType,
		Addr:   ip + ":" + port,
		Config: conf,
		Value:  msg,
	}
	if isService {
		dataFrame.Style = "serve"
	} else {
		dataFrame.Style = "scan"
	}
	logger.SLog.Infof("RequestData send:=%v", dataFrame)
	return send(dataFrame)
}

func send(dataFrame serialdata.DataFrame) ([]byte, error) {
	b, err := serialdata.SendSerialMsg(dataFrame)
	return b, err
}
